import {Image, View,Canvas} from "@tarojs/components";
import {useEffect, useState} from "react";
import Taro from "@tarojs/taro";

export default ({seatData=[],initData={},selectSeat=[],seatPadding=2}) => {

  const [inited,setInited] = useState(false)
  const [seatParts,setSeatParts] = useState([])

  /**
   * 将画布转图片
   * @param part
   * @returns 图片
   */
  const drawPart=(part)=>{
    if(process.env.TARO_ENV == 'weapp'){
      let canvas = Taro.createOffscreenCanvas({type:'2d',width:part.width,height:part.height})
      const context=canvas.getContext('2d')
      for(let j=0;j<part.rows;j++){
        for(let i=0;i<part.cols;i++){
          const seat=part.sseat[j][i]
          drawSeat(context,seat,j,i)
        }
      }
      return context.canvas.toDataURL()
    }
    let canvas = {}
    if(process.env.TARO_ENV == 'tt') canvas = tt.createSelectorQuery()
    if(process.env.TARO_ENV == 'h5') canvas = Taro.createSelectorQuery()
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        canvas.select("#myCanvas").node().exec((res) => {
            const canvas = res[0].node;
            const context = canvas.getContext('2d');
            canvas.width = part.width;
            canvas.height = part.height;
            for(let j=0;j<part.rows;j++){
              for(let i=0;i<part.cols;i++){
                const seat=part.sseat[j][i]
                drawSeat(context,seat,j,i)
              }
            }
            resolve(context.canvas.toDataURL());
        });
      }, 500);
    });
  }

  /**
   * 画座位
   * @param context
   * @param seat
   * @param j
   * @param i
   * @returns {Promise<void>}
   */
  const drawSeat=async(context,seat,j,i)=>{
    if (seat){
      let imgUrl = initData.imgResource[seat.label]
      if(initData?.cateArr && seat.label == "unselected"){
        imgUrl = initData.cateArr[seat?.priceId]
      }
      context.drawImage(imgUrl,i*initData.seatSize.w+seatPadding,j*initData.seatSize.h+seatPadding,initData.seatSize.w-2*seatPadding,initData.seatSize.h-2*seatPadding)
    }
  }

  useEffect(() => {
    Taro.showLoading({title:'加载中...'})
    if(seatData.length&&!inited){
      Promise.all(seatData.map(async area => {
        try {
          return {
            src: await drawPart({
                ...area,
                width: area.cols * initData.seatSize.w,
                height: area.rows * initData.seatSize.h
            }),
            areaName: area.areaName,
            style: `left:${area.x}px;top:${area.y}px;transform:rotate(${area.rotation}deg);width:${area.cols * initData.seatSize.w}px;height:${area.rows * initData.seatSize.h}px;`
          }
        } catch (error) {
            console.error('Error in processing area:', error);
            return null;
        }
      })).then(res=>{
        setSeatParts(res)
        setInited(true)
        Taro.hideLoading()
      })
    }
  }, [initData,seatData]);


  return (
    <View className='canvas-seats' style={`width:${initData.bgWidth}px;height:${initData.bgHeight}px;`}>
      {process.env.TARO_ENV != 'weapp'?<Canvas className="canvas-node" id="myCanvas" type="2d"></Canvas>:null}
      <Image class='bg' src={initData.bg}></Image>
      {
        seatParts?.map((part,index)=>{
          return (
            <View class='area-map' style={part.style} key={index}>
              <View class='area-name'>{part.areaName}</View>
              <Image class='area-bg' src={part.src}></Image>
              {
                selectSeat.filter(item=>item.areaId==index).map(item=>{
                  return (
                    <Image class='seat-item' src={initData.resource[item.label]} style={`left:${item.pos.col*initData.seatSize.w+seatPadding}px;top:${item.pos.row*initData.seatSize.h+seatPadding}px;width:${initData.seatSize.w-2*seatPadding}px;height:${initData.seatSize.h-2*seatPadding}px;`}></Image>
                  )
                })
              }
            </View>
          )
        })
      }
    </View>
  )
}
